$(document).ready(
    function(){
        
        function isMobile(){
            return $(".windowWidth").css("float") !== "none";
        }
        
        function formatDeviceLayout(){
            var content = $(".responsive-table tbody");
            if(isMobile()){
                $("#search-box").attr("placeholder", "Søk");
            } else{
                content.css("display", "true");
                $("#search-box").attr("placeholder", "Søk etter bar eller sted");
            }
        };
        
        formatDeviceLayout();
        
        $(window).resize(function(){
            formatDeviceLayout();
        });
        
        var UI = {};
        (function (UI) {
            
            UI.start = function(){
                
                function getUserPos(){
                    var dfd = new $.Deferred();
                    var userPos = null;

                    if(navigator.geolocation){
                        navigator.geolocation.getCurrentPosition(
                            function(position){
                                userPos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
                                dfd.resolve(userPos);
                            }
                        );
                    } else{
                        dfd.resolve(userPos);
                    }

                    return dfd.promise();
                }
                
                var args = {
                    action : 'Select'
                };
                
                $.when(Actions.barOverviewFetch(args), Actions.getPlaces(args)).then(function(barItems, placeItems) {
                    var tags = [];
                    for(var bar in barItems){
                        var bar = barItems[bar];
                        tags.push({label : bar.name, desc : "Bar"});
                    }
                    
                    for(var place in placeItems){
                        var place = placeItems[place];
                        var name = place.name;
                        
                        name = name.toLowerCase().replace(/([^a-zæøå])([a-zæøå])(?=[a-zæøå]{2})|^([a-zæøå])/g, function(_, g1, g2, g3) {
                            return (typeof g1 === 'undefined') ? g3.toUpperCase() : g1 + g2.toUpperCase();
                        });
                        tags.push({label : name, desc : "Sted"});
                    }
                    
                    $("#search-box").autocomplete({
                        source: tags,
                        open: function(){
                            if($(".windowWidth").css("float") === "none" ){
                                $(".ui-menu-item").width($("#search-box").width());
                            } else{
                                $(".ui-menu-item").width($(window).width());
                            }
                        },
                        select: function(event, ui){
                            $("#search-box").val(ui.item.value);
                            $("#searchBtn").click();
                        }
                    }).autocomplete("instance")._renderItem  = function(li, item){
                        return $("<li>").append("<span class='item-label'>" + item.label + "</span><span class='item-desc'>" + item.desc + "</span>").appendTo(li);
                    };
                });
                
                $.when(Actions.getTopRatedBars(args)).then(
                    function(returnItems){
                        //Create the top hit
                        var topBar = returnItems[0];
                        var htmlTopBar = "";
                        if(topBar.image !== ""){
                            var base64String = "data:" + topBar.image_type + ";base64," + topBar.image;
                            $("#top-rated-top-hit-img").attr("src", base64String);
                        }
                        htmlTopBar += "<div style='font-size: 24px; text-align: left;'><a href='../pages/barProfile.php?barid=" + topBar.bar_id + "'>" + topBar.name + "</a></div>";
                        var rating = Number(topBar.rating);
                        htmlTopBar += "<div title='" + rating + " / 5 ' style='text-align: left;'>";
                        var counter = 1;
                        while(counter <= 5){
                            if(rating >= counter){
                                htmlTopBar += "<img class='rating-stars-content-box' src='../resources/images/rating-star.png'>";
                            } else {
                                htmlTopBar += "<img src='../resources/images/rating-star.png' class='grayscale rating-stars-content-box'>";
                            }
                            counter++;
                        }
                        htmlTopBar += "</div>";
                        htmlTopBar += "<div style='font-size: 20px; text-align: left;'>" + topBar.place + "</div>";
                        htmlTopBar += "<div style='font-size: 16px; text-align: left; font-style: italic;'>" + limitCharacters(topBar.description, 70) + "</div>";
                        $("#top-rated-top-hit").append(htmlTopBar);

                        //Create the remaining hits
                        var topRated = returnItems.slice(1,10);
                        for(var bar in topRated){
                            var bar = topRated[bar];
                            var html = "<tr>";
                            html += "<td><a href='../pages/barProfile.php?barid=" + bar.bar_id + "'>" + bar.name + "</a></td>";
                            html += "<td>" + bar.place + "</td>";
                            var rating = Number(bar.rating);
                            html += "<td title='" + rating + " / 5 '>";
                            var counter = 1;
                            while(counter <= 5){
                                if(rating >= counter){
                                    html += "<img class='rating-stars-content-box' src='../resources/images/rating-star.png'>";
                                } else {
                                    html += "<img src='../resources/images/rating-star.png' class='grayscale rating-stars-content-box'>";
                                }
                                counter++;
                            }
                            html += "</td>";
                            html += "<td>" + bar.age_limit + "</td>";
                            html += "</tr>";
                            $("#top-rated-bars").append(html);
                        }
                        $.when(getNearbyBars(returnItems)).then(
                            function(nearbyBars){
                                //Create the top hit
                                var topBar = nearbyBars[0];
                                var htmlTopBar = "";
                                if(topBar.image !== "") $("#top-rated-nearby-top-hit-img").attr("src", "data:" + topBar.image_type + ";base64," + topBar.image);
                                htmlTopBar += "<div style='font-size: 24px; text-align: left;'><a href='../pages/barProfile.php?barid=" + topBar.bar_id + "'>" + topBar.name + "</a></div>";
                                var rating = Number(topBar.rating);
                                htmlTopBar += "<div title='" + rating + " / 5 ' style='text-align: left;'>";
                                var counter = 1;
                                while(counter <= 5){
                                    if(rating >= counter){
                                        htmlTopBar += "<img class='rating-stars-content-box' src='../resources/images/rating-star.png'>";
                                    } else {
                                        htmlTopBar += "<img src='../resources/images/rating-star.png' class='grayscale rating-stars-content-box'>";
                                    }
                                    counter++;
                                }
                                htmlTopBar += "</div>";
                                htmlTopBar += "<div style='font-size: 20px; text-align: left;'>" + topBar.address + " (" + Number(topBar.distance).toFixed(2) + " km)" + "</div>";
                                htmlTopBar += "<div style='font-size: 16px; text-align: left; font-style: italic;'>" + limitCharacters(topBar.description, 70) + "</div>";
                                $("#top-rated-nearby-top-hit").append(htmlTopBar);
                                
                                //Create the remaining hits
                                console.log(nearbyBars[1]);
                                var nearbyBars = nearbyBars.slice(1,10);
                                for(var bar in nearbyBars){
                                    var bar = nearbyBars[bar];
                                    console.log(bar);
                                    var html = "<tr>";
                                    html += "<td><a href='../pages/barProfile.php?barid=" + bar.bar_id + "'>" + bar.name + "</a></td>";
                                    html += "<td>" + Number(bar.distance).toFixed(2) + " km </td>";
                                    var rating = Number(bar.rating);
                                    html += "<td title='" + rating + " / 5 '>";
                                    var counter = 1;
                                    while(counter <= 5){
                                        if(rating >= counter){
                                            html += "<img class='rating-stars-content-box' src='../resources/images/rating-star.png'>";
                                        } else {
                                            html += "<img src='../resources/images/rating-star.png' class='grayscale rating-stars-content-box'>";
                                        }
                                        counter++;
                                    }
                                    html += "</td>";
                                    html += "<td>" + bar.age_limit + "</td>";
                                    html += "</tr>";
                                    $("#top-rated-bars-nearby").append(html);
                                }
                            }
                        );
                    }
                );
                    
                function limitCharacters(text, limit){
                    if(text.length > limit){
                        return text.substr(0, limit) + "...";
                    }else{
                        return text;
                    }
                }
                    
                function getNearbyBars(bars){
                    var barsNearby = [];
                    var userPos;
                    var dfd = new $.Deferred();
                    $.when(getUserPos()).then(
                        function(userItems){  
                            for(var bar in bars){
                                var bar = bars[bar];
                                
                                var latLng = bar.latlong.substring(1,bar.latlong.length-1).split(",");
                                var latLong = {
                                    lat: Number(latLng[0]),
                                    lng: Number(latLng[1])
                                };
                                
                                latLong = new google.maps.LatLng(latLong.lat, latLong.lng);
                                
                                var distance = getDistance(latLong, userItems)/1000;
                                bar.distance = distance;
                                if(distance < 5) barsNearby.push(bar);
                            }
                            dfd.resolve(barsNearby);
                        }
                    );
                    return dfd.promise();
                }
                
                var rad = function(x) {
                    return x * Math.PI / 180;
                };

                var getDistance = function(p1, p2) {
                    var R = 6378137; // Earth’s mean radius in meter
                    var dLat = rad(p2.lat() - p1.lat());
                    var dLong = rad(p2.lng() - p1.lng());
                    var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
                      Math.cos(rad(p1.lat())) * Math.cos(rad(p2.lat())) *
                      Math.sin(dLong / 2) * Math.sin(dLong / 2);
                    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
                    var d = R * c;
                    return d; // returns the distance in meter
                };

                
        
                $.when(Actions.getTopBudgetBars(args)).then(
                    function(returnItems){
                        for(var bar in returnItems){
                            var bar = returnItems[bar];
                            var html = "<tr>";
                            html += "<td><a href='../pages/barProfile.php?barid=" + bar.bar_id + "'>" + bar.name + "</a></td>";
                            html += "<td>" + bar.place + "</td>";
                            var rating = Number(bar.rating);
                            html += "<td title='" + rating + " / 5 '>";
                            var counter = 1;
                            while(counter <= 5){
                                if(rating >= counter){
                                    html += "<img class='rating-stars-content-box' src='../resources/images/rating-star.png'>";
                                } else {
                                    html += "<img src='../resources/images/rating-star.png' class='grayscale rating-stars-content-box'>";
                                }
                                counter++;
                            }
                            html += "</td>";
                            
                            if(Number(bar.cover_charge) === 0){
                                html += "<td>-</td>";
                            } else{
                                html += "<td>" + bar.cover_charge + "</td>";
                            }
                            if(Number(bar.beer_price) === 0){
                                html += "<td>-</td>";
                            } else{
                                html += "<td>" + bar.beer_price + "</td>";
                            }
                            html += "</tr>";
                            $("#top-budget-bars").append(html);
                        }
                    }
                );
                    
                $.when(Actions.getCloseHappenings(args)).then(
                    function(returnItems){
                        for (var happening in returnItems){
                            var h = returnItems[happening];
                            var html = "<tr>";
                            html += "<td><a href='../pages/barProfile.php?barid=" + h.bar_id + "'>" + h.name + "</a></td>";
                            html += "<td><a href='../pages/barProfile.php?barid=" + h.bar_id + "'>" + h.bar_name + "</a></td>";
                            html += "<td>" + h.date + "-" + h.time + "</td>";
                            html += "<td>" + h.price + "</td>";
                            html += "<td style='width: 60%;'>" + h.description + "</td>";
                            html += "</tr>";
                            $("#happenings-near-you").append(html);
                        }
                    }
                );
            };
            
        }(UI));
        var Helpers = {};
        (function (Helpers) {
            
            
            
        }(Helpers));
        
        var Actions = {};
        (function (Actions) {
            
            Actions.barOverviewFetch = function(args) {
                var dfd = new $.Deferred();
                $.ajax({
                    type: "GET",
                    url: "../resources/helpers/barOverviewFetch.php",
                    data: args,
                    cache: false,
                    success: function(data){
                        data = JSON.parse(data);
                        dfd.resolve(data);
                    }
                });
                return dfd.promise();
            };
            
            Actions.getPlaces = function(args) {
                var dfd = new $.Deferred();
                $.ajax({
                    type: "GET",
                    url: "../resources/helpers/getPlaces.php",
                    data: args,
                    cache: false,
                    success: function(data){
                        data = JSON.parse(data);
                        dfd.resolve(data);
                    }
                });
                return dfd.promise();
            };
            
            Actions.getTopRatedBars = function(args) {
                var dfd = new $.Deferred();
                $.ajax({
                    type: "GET",
                    url: "../resources/helpers/getTopRatedBars.php",
                    data: args,
                    cache: false,
                    success: function(data){
                        data = JSON.parse(data);
                        dfd.resolve(data);
                    }
                });
                return dfd.promise();
            };
            
            Actions.getTopBudgetBars = function(args) {
                var dfd = new $.Deferred();
                $.ajax({
                    type: "GET",
                    url: "../resources/helpers/getTopBudgetBars.php",
                    data: args,
                    cache: false,
                    success: function(data){
                        data = JSON.parse(data);
                        dfd.resolve(data);
                    }
                });
                return dfd.promise();
            };
            
            Actions.getCloseHappenings = function(args) {
                var dfd = new $.Deferred();
                $.ajax({
                    type: "GET",
                    url: "../resources/helpers/getCloseHappenings.php",
                    data: args,
                    cache: false,
                    success: function(data){
                        data = JSON.parse(data);
                        dfd.resolve(data);
                    }
                });
                return dfd.promise();
            };
            
        }(Actions));
        
        var Controller = {};
        (function (Controller) {
            
            var expandContentBox = function(){
                if($(".windowWidth").css("float") === "none" ){
                    return;
                }
                var content = $(this).closest(".content-box").find(".responsive-table tbody");
                if(content.css("display") === "none"){
                    content.css("display", "block");
                } else{
                    content.css("display", "none");
                }  
            };
            
            function searchBtnClicked(){
                var url = "http://localhost/barcrawl/pages/findBar.php?#search=";
                url += $("#search-box").val();
                window.location.assign(url);
            }
            
            Controller.init= function(){
                $("#top-rated-bars-header").unbind("click").bind("click", expandContentBox);
                $("#top-budget-bars-header").unbind("click").bind("click", expandContentBox);
                $("#happenings-near-you-header").unbind("click").bind("click", expandContentBox);
                $("#searchBtn").unbind("click").bind("click", searchBtnClicked);
                $(document).keypress(function(e){
                    if(e.which === 13 && $("#search-box").is(":focus")){
                        $("#searchBtn").click().focus();
                    }
                });
            };
            
        }(Controller));	
        
        UI.start();
        Controller.init();
    }
);